/**
 * Filename: AlbumMusicPhotoFragment.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/5/16 15:49
 */
package com.github.postsanf.yinian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.AlbumStatusActivity;
import com.github.postsanf.yinian.adapter.MusicAlbumAdapter;
import com.github.postsanf.yinian.bean.YNMusicAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNMusicStatusResponse;
import com.github.postsanf.yinian.service.MusicStatusService;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import jp.wasabeef.recyclerview.animators.ScaleInAnimator;

//音乐相册动态页
public class AlbumMusicPhotoFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, AppBarLayout.OnOffsetChangedListener {
    private View view;                        // 上下文视图
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshlayout;
    private WrapContentLinearLayoutManager mLinearLayoutManager;
    private MusicAlbumAdapter mAdapter;                    // 适配器
    private LinkedList<YNMusicAlbum> mMusicPhotos;               // 音乐相册数据
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    private boolean isBottom;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        registerBroadcastReceiver();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMusicPhotos = new LinkedList<>();
//      noticeServiceInit();
        initView();
        initData();
        return view;
    }

    private void initData() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_MA_ID, CommonConstants.YN_ZERO);
        mParam.put(CommonConstants.YNS_INFO_TYPE, CommonConstants.YNS_SIGN_INITS);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowMusicAlbums))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNMusicStatusResponse resMusicStatus = gson.fromJson(s, YNMusicStatusResponse.class);
                        if (resMusicStatus != null && ReqUtils.isSuccess(resMusicStatus.getCode())) {
                            mMusicPhotos.addAll(resMusicStatus.getData());
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onEnd(Response<String> response) {
                        super.onEnd(response);
                        mRefreshlayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_activity_music_album, null);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.music_status_recyclerview);

        mRefreshlayout = (SwipeRefreshLayout) view.findViewById(R.id.music_status_swipe_refresh);
        mRefreshlayout.setColorSchemeColors(getResources().getColor(R.color.yncolor));
        mRefreshlayout.setOnRefreshListener(this);
        mRefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        // 初始加载刷新
        mRefreshlayout.setRefreshing(true);

        mLinearLayoutManager = new WrapContentLinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setItemAnimator(new ScaleInAnimator(new OvershootInterpolator(1f)));
        mRecyclerView.getItemAnimator().setAddDuration(300);
        mRecyclerView.getItemAnimator().setRemoveDuration(300);
        mRecyclerView.getItemAnimator().setMoveDuration(300);
        mRecyclerView.getItemAnimator().setChangeDuration(300);

        // 设置适配器
        mAdapter = new MusicAlbumAdapter(getActivity(), mMusicPhotos, application.getCurGid());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setHasFixedSize(true);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        mRecyclerView.setAdapter(mYNRecyclerViewAdapter);

        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                ((AlbumStatusActivity) getActivity()).showActionButton(dy < 0);
            }
        });

        mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    return;
                }

                // 加载中，返回
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }

                // 加载下一页
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, 10, LoadingFooter.State.Loading, null);
                mRecyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadStatus();
                    }
                }, 1000);
            }
        });
    }

    private void loadStatus() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_MA_ID, String.valueOf(mMusicPhotos.size() > 0 ? mMusicPhotos.get(mMusicPhotos.size() - 1).getMaID() : 0));
        mParam.put(CommonConstants.YNS_INFO_TYPE, CommonConstants.YNS_SIGN_LOAD);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowMusicAlbums))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNMusicStatusResponse resMusicStatus = gson.fromJson(s, YNMusicStatusResponse.class);
                        if (resMusicStatus != null && ReqUtils.isSuccess(resMusicStatus.getCode())) {
                            for (int i = 0; i < resMusicStatus.getData().size(); i++) {
                                mMusicPhotos.addLast(resMusicStatus.getData().get(i));
                            }
                            if (resMusicStatus.getData().size() == 0) {
                                isBottom = true;
                                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, 10, LoadingFooter.State.TheEnd, null);
                            } else {
                                RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onEnd(Response<String> response) {
                        super.onEnd(response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 更新成员数据
    private void updateView(List<YNMusicAlbum> memberList) {
        mMusicPhotos.addAll(memberList);
        mAdapter.notifyDataSetChanged();
    }

    // 分析并执行动作
    BroadcastReceiver mMusicPhotoBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                //　加载成员数据
//                case ACTIONs.actionMemberUpdate:
//                    List<YNMusicAlbum> memberList = (List<YNMusicAlbum>) intent.getSerializableExtra(ACTIONs.aAddData);
//                    updateView(memberList);
//                    break;
                case ACTIONs.actionFreshMusicStatus:
                    int groupID = intent.getIntExtra(ACTIONs.StatusId, 0);
                    if (groupID == application.getCurGid()) {
                        onRefresh();
                    }
                    break;
            }
        }
    };

    // 注册接收者
    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionFreshMusicStatus);
        getActivity().registerReceiver(mMusicPhotoBroadcastReceiver, myIntentFilter);
    }

    // 通知后台加载数据
    private void noticeServiceInit() {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), MusicStatusService.class);
        mIntent.setAction(ACTIONs.actionMusicStatus);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        getActivity().startService(mIntent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mMusicPhotoBroadcastReceiver);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
        if (i == 0) {
            mRefreshlayout.setEnabled(true);
        } else {
            mRefreshlayout.setEnabled(false);
        }
    }

    @Override
    public void onRefresh() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_MA_ID, String.valueOf(mMusicPhotos.size() > 0 ? mMusicPhotos.get(0).getMaID() : 0));
        mParam.put(CommonConstants.YNS_INFO_TYPE, CommonConstants.YNS_SIGN_REFRESH);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowMusicAlbums))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNMusicStatusResponse resMusicStatus = gson.fromJson(s, YNMusicStatusResponse.class);
                        if (resMusicStatus != null && ReqUtils.isSuccess(resMusicStatus.getCode())) {
                            for (int i = resMusicStatus.getData().size() - 1; i >= 0; i--) {
                                mMusicPhotos.addFirst(resMusicStatus.getData().get(i));
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onEnd(Response<String> response) {
                        super.onEnd(response);
                        mRefreshlayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }
}